package cn.longwingstech.intelligence.agent.langchain4j;

import dev.langchain4j.service.TokenStream;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
@Component
public class SuperAgent {
    @Resource
    private SuperAiServiceFactory superAiServiceFactory;
    public Flux<String> chat(String message, String chatId) {
        SuperAiService superAiService = superAiServiceFactory.createSuperAiService(chatId);
        TokenStream stream = superAiService.chat(chatId,message);
        return Flux.create(sink -> {
            stream.onPartialResponse(sink::next)
                    .onToolExecuted(toolExecutionResult -> {
                        // 处理工具执行结果
                        sink.next("\n"+"【调用工具】" + toolExecutionResult.request().name()+ "\n");
                        sink.next("\n\n");
//                        System.err.println("【工具调用】" + toolExecutionResult.request().name());
                    })
                    .onPartialThinking(thinking -> {
                        sink.next("\n" + "<think>" + thinking.text() +"</think>");
                    })
                    .beforeToolExecution(beforeToolExecution -> {
                        // 处理工具执行前的数据
//                        sink.next("\n" + "【选择工具】" + beforeToolExecution.request().name()+ "\n");
//                        System.err.println("【选择工具】" + beforeToolExecution.request().name());
                    })
                    .onCompleteResponse(chatResponse -> {
                        // 处理完整响应
                        sink.complete();
                    })
                    .onError(sink::error)
                    .start();
        });
    }
}
